package com.front.session;

import java.io.Serializable;
import java.text.SimpleDateFormat;

import org.apache.shiro.session.Session;
import org.crazycake.shiro.RedisSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;

import com.front.common.StringUtils;
import com.front.constant.UserConstant;
import com.front.web.shiro.model.User;
import com.front.web.shiro.service.UserService;

/***
 * 
 * @author huang
 *
 */
public class ClusterUserSessionDao extends RedisSessionDAO
{
    @Autowired
    private UserService userService;
    
    protected Session doReadSession(Serializable sessionId)
    {
        Session session = super.doReadSession(sessionId);
        if(session!=null)
        {
        	  Object userName = session.getAttribute("org.apache.shiro.subject.support.DefaultSubjectContext_PRINCIPALS_SESSION_KEY");
              if (!StringUtils.isEmpty(userName))
              {
            	  String loginName =StringUtils.obj2String(userName);
            	  User user =userService.findByUserName(loginName);
                  if(user!=null)
                  {
                	  if(user.getIsOnline()==UserConstant.USER_OFF_LINE)
                	  {
                		  userService.setUserLine(loginName, UserConstant.USER_ON_LINE);
                	  }
                  }
                  else
                  {
                	     userService.setUserLine(loginName, UserConstant.USER_OFF_LINE);
                  }
              }
        }
        return session;
    }

    
    @Override
    protected Serializable doCreate(Session session) {
    	Serializable sess= super.doCreate(session);
    	return sess;
    }

    public void delete(Session session)
    {
        if (null != session)
        {
            try
            {
                Object userName = session
                        .getAttribute("org.apache.shiro.subject.support.DefaultSubjectContext_PRINCIPALS_SESSION_KEY");
                if (!StringUtils.isEmpty(userName))
                {
                    userService.setUserLine(userName.toString(), UserConstant.USER_OFF_LINE);
                }
            }
            catch (Exception e)
            {
                System.err.println(e.getMessage());
            }
            super.delete(session);
        }
    }
    
}
